package com.wisdytech.linkdcs.tool.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.constants.DictKeyConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.dao.ToolCheckDetailDao;
import com.wisdytech.linkdcs.tool.dao.ToolCheckItemDao;
import com.wisdytech.linkdcs.tool.dao.ToolCheckRecordDao;
import com.wisdytech.linkdcs.tool.dao.TtEqToolDao;
import com.wisdytech.linkdcs.tool.model.ToolCheckDetail;
import com.wisdytech.linkdcs.tool.model.ToolCheckItem;
import com.wisdytech.linkdcs.tool.model.ToolCheckRecord;
import com.wisdytech.linkdcs.tool.model.TtEqTool;
import com.wisdytech.linkdcs.tool.service.IToolCheckRecordService;
import com.wisdytech.linkdcs.tool.vo.ToolCheckItemVO;
import com.wisdytech.linkdcs.tool.vo.ToolCheckVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-13
 */
@Service
@Transactional
public class ToolCheckRecordServiceImpl extends BaseService<ToolCheckRecordDao, ToolCheckRecord> implements IToolCheckRecordService {

    @Resource
    private ToolCheckRecordDao toolCheckRecordDao;

    @Resource
    private ToolCheckDetailDao toolCheckDetailDao;
	@Resource
    private ToolCheckItemDao toolCheckItemDao;

    @Resource
    private TtEqToolDao ttEqToolDao;

    @Override
    public Boolean toolCheck(ToolCheckVO vo, SysUser operator) {
        Integer operatorCount = 0;
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        if (vo == null || StringUtils.isBlank(vo.getToolCode()))
            throw new ServiceException("参数错误");

        //保存保养记录
        ToolCheckRecord record = new ToolCheckRecord();
        record.setToolCode(vo.getToolCode());
        String pkId = BaseUtil.getUUID();
        record.setPkId(pkId);
        record.setDelFlag(CommonConstants.DEL_FLAG);
        record.setCreateDate(new Date());
        record.setCreateUser(operator.getUsername());
        record.setCheckUser(vo.getCheckUser());
        record.setCheckDate(vo.getCheckDate());
        record.setConfirmUser(vo.getConfirmUser());
        record.setConfirmDate(vo.getConfirmDate());
        record.setRemark(vo.getRemark());
        operatorCount = toolCheckRecordDao.insert(record);

        //保存保养项明细
        List<ToolCheckItemVO> list = vo.getCheckItemList();
        for (ToolCheckItemVO itemVO : list) {
            ToolCheckDetail detail = new ToolCheckDetail();
            detail.setPkId(BaseUtil.getUUID());
            detail.setCreateUser(operator.getUsername());
            detail.setCreateDate(new Date());
            detail.setDelFlag(CommonConstants.DEL_FLAG);
            detail.setRecordId(pkId);
			// 查询当前该保养项的快照版本
            ToolCheckItem item = toolCheckItemDao.selectById(itemVO.getCheckItemId());
            // 关联id改为version，即当前版本快照的id
            detail.setItemId(item.getVersion());

            detail.setCheckResult(itemVO.getCheckResult());
            //TODO 循环操作数据库 应该改成 一次批量插入 但是mysql和oracle批量插入数据的语法不同，为兼容暂且如果
            toolCheckDetailDao.insert(detail);
        }

        //更新下次保养日期和上次保养日期
        TtEqTool tool = new TtEqTool();
        TtEqTool params = new TtEqTool();
        params.setToolCode(vo.getToolCode());
        params.setDelFlag(CommonConstants.DEL_FLAG);
        //查询该工装保养周期
        TtEqTool t = ttEqToolDao.selectOne(params);
        //上次校验日期为这次校验日期
        tool.setLastCheckoutDate(vo.getCheckDate());
        //下次校验日期为这次校验日期加校验周期
        tool.setNextCheckoutDate(getAfterDate(t.getCheckoutCycle().intValue(), vo.getCheckDate()));

        //hack 方法 因为在TtEqTool中设置了mp的FieldStrategy 为ignore用来更新空值，所以此处如果不加的话，值会被更新掉，慎用
        tool.setMaintainCycle(t.getMaintainCycle());
        tool.setCheckoutCycle(t.getCheckoutCycle());
        EntityWrapper<TtEqTool> ew = new EntityWrapper<>();
        ew.eq("tool_code", vo.getToolCode())
                .eq("del_flag", CommonConstants.DEL_FLAG);
        ttEqToolDao.update(tool, ew);
        return operatorCount > 0;
    }

    @Override
    public PageInfo<TtEqTool> getToolCheckRecordByFilter(String toolCode, String toolName, String toolModel, String toolType, String opCode, String checkDateStart, String checkDateEnd, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("toolTypeParentKey", DictKeyConstants.TOOL_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(toolCode)) {
            params.put("toolCode", toolCode);
        }
        if (StringUtils.isNotBlank(toolName)) {
            params.put("toolName", toolName);
        }
        if (StringUtils.isNotBlank(toolModel)) {
            params.put("toolModel", toolModel);
        }
        if (StringUtils.isNotBlank(toolType)) {
            params.put("toolType", toolType);
        }
        if (StringUtils.isNotBlank(opCode)) {
            params.put("opCode", opCode);
        }
        if (StringUtils.isNotBlank(checkDateStart)) {
            params.put("checkDateStart", checkDateStart);
        }
        if (StringUtils.isNotBlank(checkDateEnd)) {
            params.put("checkDateEnd", checkDateEnd);
        }
        List<TtEqTool> list = this.beforeList(TtEqToolDao.class, filter).getToolCheckedList(params);
        return new PageInfo<>(list);
    }

    @Override
    public ToolCheckVO getToolCheckResult(String pkId) {
        if (StringUtils.isBlank(pkId)) {
            return null;
        }
        //查询工装校验信息
        ToolCheckRecord record = toolCheckRecordDao.getToolCheckRecord(pkId);
        if (record == null) {
            throw new ServiceException("校验记录不存在");
        }
        ToolCheckVO vo = new ToolCheckVO();
        vo.setToolCode(record.getToolCode());
        vo.setToolName(record.getToolName());
        vo.setCheckUserWorkNo(record.getCheckUserWorkNo());
        vo.setCheckUser(record.getCheckUser());
        vo.setCheckDate(record.getCheckDate());
        vo.setConfirmDate(record.getConfirmDate());
        vo.setConfirmUser(record.getConfirmUser());
        vo.setRemark(record.getRemark());
        vo.setCheckResult(record.getCheckResult());
        //查询检验项明细
        List<ToolCheckItemVO> list = this.toolCheckDetailDao.getCheckResultDetail(record.getPkId());
        vo.setCheckItemList(list);
        return vo;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past 天数
     * @return Date
     */
    private Date getAfterDate(int past, Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        return calendar.getTime();
    }
}
